﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BackGroundWorker
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        }

        void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            foreach (var item in getItems())
            {
                AddListBoxItem(item);
            }
        }

        private delegate void AddListBoxItemDelegate(string item);
        private void AddListBoxItem(string item)
        {    
            if (this.listBox1.InvokeRequired)    
            {        
                // This is a worker thread so delegate the task.        
                this.listBox1.Invoke(new AddListBoxItemDelegate(this.AddListBoxItem), item);     
            }    
            else    
            {        // This is the UI thread so perform the task.        
                this.listBox1.Items.Add(item);    
            }
        } 


        private List<string> getItems()
        {
            List<string> res = new List<string>();

            for (int i = 1; i <= 1000; i++)
                res.Add("THis is item number " + i.ToString());
           
            return res;
        }
    }
}
